import React, { useState, useEffect } from 'react'
import {
  Button,
  Form,
  Input,
  InputNumber,
  TextArea,

} from '@nutui/nutui-react-taro'
import { View, Text } from '@tarojs/components'
import { Address, Cell, Switch } from '@nutui/nutui-react-taro'
import province from 'china-area-data'
// import { FormItemRuleWithoutValidator } from '@/packages/formitem/types'
import { Address as AddressInfo } from '../../../types/address'
import { saveAddress, updateAddress } from '../../../api/address'
import { showLoading, hideLoading } from '@tarojs/taro'
interface Item {
  text: string,
  value: string | number,
  children?: Array<Item>
}
interface IProps {
  setShowBottom: (e: boolean) => void
  valueInfo: AddressInfo
  onConfirm: (e: boolean) => void
  isAdd?: boolean
}
const AddressEdit = (props: IProps) => {
  const { setShowBottom, valueInfo, onConfirm, isAdd = false } = props
  const [addressInfo, setAddressInfo] = useState<AddressInfo>({
    contact_phone: '',//联系电话
    recipient_name: "",//收货人姓名
    province: '',//省份名称
    city: '',//城市名称
    district: '',//区县名称
    street: '',//街道名称
    province_id: 0,// 省级id
    city_id: 0,//市级id
    district_id: 0,//县级id
    street_id: 0,//街道id
    detail_address: "",//详细地址
    is_default: 0,//是否默认地址 1 是 0否
    address_type: 0,// 地址类型 0 个人 1 企业 2 收货地址 3 发票地址
  })
  const [text, setText] = useState('请选择地址')
  const [visible, setVisible] = useState(false)
  const [form] = Form.useForm()
  const [dataAddressList, setDataAddressList] = useState<Array<Item>>([])
  const handleData_ = (value, j) => {
    let obj = {}
    for (let i in value) {
      obj[i] = {
        children: Object.values(handleData_(province[i], i)),
        text: province[j][i],
        value: Number(i)
      }
    }
    return obj
  }

  const handleData = (province) => {
    let parent = province['86']
    let parent_city = {}
    for (let i in parent) {
      parent_city[i] = {
        children: Object.values(handleData_(province[i], i)),
        text: parent[i],
        value: Number(i)
      }

    }
    return Object.values(parent_city) as Array<Item>
  }
  if (dataAddressList.length <= 0) {
    setDataAddressList(handleData(province))
  }
  useEffect(() => {
    if (valueInfo.id) {
      setAddressInfo({ ...valueInfo })
      setText(`${valueInfo.province}`)
      form.setFieldsValue({ ...valueInfo })
    } else {
      setAddressInfo({})
      form.resetFields()
      setText('请选择地址')
      // form.validateFields()
    }
  }, [valueInfo])
  return (
    <>
      <Form
        form={form}
        onFinish={async (values) => {
          showLoading()
          let { data, success } = addressInfo.id ? await updateAddress({ ...addressInfo, ...values }) : await saveAddress({ ...addressInfo, ...values })

          if (success) {
            onConfirm(true)
            setAddressInfo({})
            setText('请选择地址')
            form.resetFields()
            form.validateFields()
          }
          hideLoading()
        }}
        labelPosition="right"
        initialValues={addressInfo}
        footer={
          <>
            <Button nativeType="submit" block type="primary" >
              提交
            </Button>
          </>
        }
      >
        <Form.Item
          align="center"
          required
          label="所在地区"
          name="province"
          rules={[{ required: true, message: '请选择所在地区' }]}
        >
          <Cell

            title=""
            description={text}
            onClick={() => setVisible(true)}
          />

        </Form.Item>
        <Form.Item
          align="center"
          required
          label="手机号码"
          name="contact_phone"
          rules={[
            { max: 11, message: '请输入正确的手机号码' },
            { required: true, message: '手机号码' },
            {
              validator: (
                ruleCfg,
                value: string
              ) => {
                return value?.length > 5
              },
            },
          ]}
        >
          <Input
            className="nut-input-text"
            placeholder="手机号码"
            type="number"
          />
        </Form.Item>
        <Form.Item
          align="center"
          required
          label="收货人"
          name="recipient_name"
          rules={[
            { max: 11, message: '请输入收货人' },
            { required: true, message: '请输入收货人' },
          ]}
        >
          <Input
            className="nut-input-text"
            placeholder="收货人"
            type="text"
          />
        </Form.Item>
        <Form.Item
          label="详细地址"
          name="detail_address"
          rules={[
            { required: true, message: '请输入详细地址' },
          ]}
        >
          <TextArea placeholder="请输入详细地址" maxLength={100} />
        </Form.Item>
        <Form.Item label="默认地址" name='is_default'>
          <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>

            <Switch checked={addressInfo.is_default === 1} onChange={(e) => {
              form.setFieldsValue({ is_default: e ? 1 : 0 })
              setAddressInfo({ ...addressInfo, is_default: e ? 1 : 0 })
            }} />
          </View>
        </Form.Item>
      </Form>

      <Address
        visible={visible}
        options={dataAddressList}
        defaultValue={[addressInfo.province_id, addressInfo.city_id, addressInfo.district_id]}
        title="选择地址"
        onChange={(value, params) => {
          let str = params.map(item => item.text).join('-')
          let provinceObj = params[0] || {}
          let cityObj = params[1] || {}
          let districtObj = params[2] || {}
          form.setFieldsValue({
            province: str, city: cityObj.text, district: districtObj.text, street: str,
            province_id: provinceObj.value, city_id: cityObj.value, district_id: districtObj.value, street_id: 0
          }); // 更新表单值
          setText(str)
          console.log(value, params)
        }}
        onClose={() => setVisible(false)}
      />
    </>
  )
}

export default AddressEdit
